package com.example.livedata.SimpleDemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.example.livedata.R;
import com.example.livedata.ViewModel.TimeViewModel;

import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;

public class TimeAutoAddActivity extends AppCompatActivity {

    private TextView tv_time;
    private TimeViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_auto_add);
        tv_time = findViewById(R.id.tv_time);
        viewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(TimeViewModel.class);
        tv_time.setText(String.valueOf(viewModel.getTimeValue().getValue()));
        startTime();
        viewModel.getTimeValue().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                tv_time.setText(String.valueOf(integer));
            }
        });
    }

    private void startTime() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                //postValue是在非ui线程中赋值
                //setValue是在ui线程中赋值
                viewModel.getTimeValue().postValue(viewModel.getTimeValue().getValue() + 1);
            }
        }, 1000, 1000);
    }
}